<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="年-月" prop="contrastDate">
              <el-date-picker
                v-model="queryParams.contrastDate"
                type="month"
                value-format="YYYY-MM"
                placeholder="请选择"
              />
            </el-form-item>
            <el-form-item label="会计科目编码" prop="subjectCode" label-width="100">
              <el-input v-model="queryParams.subjectCode" placeholder="请输入会计科目编码" clearable
                        @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="会计科目名称" prop="subjectName" label-width="100">
              <el-input v-model="queryParams.subjectName" placeholder="请输入会计科目名称" clearable
                        @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['collect:setup:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['collect:setup:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['collect:setup:export']">
              导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="BottomRight" @click="inherit" color="green"
                       v-hasPermi="['collect:setup:inherit']">
              继承
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table border v-loading="loading" :data="setupList" @selection-change="handleSelectionChange" class="enhanced-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键id" align="center" prop="id" v-if="false" />
        <el-table-column label="年-月" align="center" prop="contrastDate" />
        <el-table-column label="会计科目编码" align="center" prop="subjectCode" />
        <el-table-column label="会计科目名称" align="center" prop="subjectName" min-width="160" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['collect:setup:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['collect:setup:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 继承弹窗 -->
    <el-dialog :title="extendDialog.title" v-model="extendDialog.visible" stripe width="400px" append-to-body>
      <el-form ref="inheritFormRef" :model="inheritData">
        <el-form-item label="继承年月" prop="inheritDate">
          <el-date-picker
            v-model="inheritData.inheritDate"
            type="month"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="目标年月" prop="targetDate">
          <el-date-picker
            v-model="inheritData.targetDate"
            type="month"
            value-format="YYYY-MM"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="text-center">
          <el-button type="primary" :loading="buttonLoading" @click="saveInherit">确定</el-button>
          <el-button @click="cancelInherit">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改特殊配置对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="setupFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="年-月" prop="contrastDate">
          <el-date-picker clearable
                          v-model="form.contrastDate"
                          type="month"
                          value-format="YYYY-MM"
                          placeholder="请选择" style="width: 100%" :disabled="dialog.title==='修改特殊配置'">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会计科目" prop="subjectCode">
          <el-select v-model="form.subjectCode" placeholder="请选择会计科目" clearable
                     :disabled="dialog.title==='修改特殊配置'" filterable @change="selectOne">
            <el-option v-for="item in subjectList" :key="item.id" :label="item.subjectCode+' - '+item.subjectName"
                       :value="item.subjectCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Setup" lang="ts">
import { addSetup, delSetup, getSetup, listSetup, saveInheritData, updateSetup } from "@/api/collect/setup";
import { SetupForm, SetupQuery, SetupVO } from "@/api/collect/setup/types";
import { getAccountList } from "@/api/budget/accountSubject";
import { AccountSubjectVO } from "@/api/budget/accountSubject/types";
import useDate from "@/hooks/useDate";
import { InheritData } from "@/api/budget/contrastDept/types";
import { verify } from "@/api/budget/contrastDept";
import { parseTime } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const setupList = ref<SetupVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const setupFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});

const initFormData: SetupForm = {
  id: undefined,
  subjectCode: undefined,
  subjectName: undefined,
  remark: undefined,
  contrastDate: undefined
};

const form = ref<SetupForm>({
  ...initFormData
});

const queryParams = ref<SetupQuery>({
  pageNum: 1,
  pageSize: 10,
  subjectCode: undefined,
  subjectName: undefined,
  contrastDate: useDate.getNow()
});

const rules = {
  subjectCode: [
    { required: true, message: "会计科目编码不能为空", trigger: "change" }
  ],
  contrastDate: [
    { required: true, message: "年/月不能为空", trigger: "change" }
  ]
};

/** 查询特殊配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSetup(queryParams.value);
  setupList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  setupFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SetupVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加特殊配置";
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SetupVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getSetup(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改特殊配置";
};

const selectOne = (value: any) => {
  form.value.subjectName = subjectList.value.find(item => item.subjectCode === value).subjectName;
};
/** 提交按钮 */
const submitForm = () => {
  setupFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSetup(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSetup(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SetupVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm("是否确认删除选中的数据项？").finally(() => loading.value = false);
  await delSetup(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download("collect/setup/export", {
    ...queryParams.value
  }, `特殊配置.xlsx`);
};

const subjectList = ref<AccountSubjectVO[]>([]);
/**
 * 会计科目下拉列表
 */
const listAccountList = async () => {
  const res = await getAccountList();
  subjectList.value = res.data;
};

//==========================================================继承===========================================================
// 继承弹窗按钮开关
const extendDialog = reactive<DialogOption>({
  visible: false,
  title: "继承"
});

// 继承数据
const inheritData = reactive<InheritData>({
  inheritDate: undefined,
  targetDate: undefined,
  type: 4
});

// 重置继承数据
const resetInheritData = () => {
  inheritData.inheritDate = undefined;
  inheritData.targetDate = undefined;
};

// 继承按钮
const inherit = () => {
  extendDialog.visible = true;
  inheritData.inheritDate = useDate.getPreviousMonth();
  inheritData.targetDate = useDate.getNow();
};

// 确认继承
const saveInherit = async () => {
  buttonLoading.value = true;
  let msg: string;
  await verify(inheritData).then(res => {
    if (res.data === 1) {
      msg = "继承年月无数据!";
    }
    if (res.data === 2) {
      msg = "目标年月已存在对照数据,是否覆盖?";
    }
    if (res.data === 3) {
      msg = "目标年月无对照数据,是否继承?";
    }
  }).then(() => {
    proxy?.$modal.confirm(msg).then(() => {
      saveInheritData(inheritData);
      proxy?.$modal.msgSuccess("操作成功");
      extendDialog.visible = false;
      getList();
    });
  }).finally(() => buttonLoading.value = false);
};

// 取消继承
const cancelInherit = () => {
  resetInheritData();
  extendDialog.visible = false;
};
onMounted(() => {
  getList();
  listAccountList();
});
</script>
<style lang="scss" scoped>


</style>
